package oj;

//另一棵树的子树：给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在，返回 true ；否则，返回 false 。
//二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。
public class Solution_572 {
    public static boolean isSameTree(TreeNode p, TreeNode q){
        //两棵树是否为空
        if(p == null && q == null){
            return true;
        }
        if(p == null || q == null){
            return false;
        }
        if(p.val != q.val){
            return false;
        }
        boolean r = isSameTree(p.left,q.left);
        if(r == false){
            return false;
        }
        r = isSameTree(p.right,q.right);
        if(r == true){
            return true;
        }else{
            return false;
        }
    }
    public static boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null && subRoot == null){
            return true;
        }
        if(root == null || subRoot == null){
            return false;
        }
        return isSameTree(root,subRoot) || isSubtree(root.left,subRoot) || isSubtree(root.right,subRoot);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode();
        TreeNode subRoot = new TreeNode();
        TreeNode n2 = new TreeNode();
        TreeNode n3 = new TreeNode();
        TreeNode n4 = new TreeNode();
        TreeNode n5 = new TreeNode();
        TreeNode r2 = new TreeNode();
        TreeNode r3 = new TreeNode();
        TreeNode r4 = new TreeNode();
        root.val = 3;
        n2.val = 4;
        n3.val = 5;
        n4.val = 1;
        n5.val = 2;
        subRoot.val = 4;
        r2.val = 1;
        r3.val = 2;
        root.left = n2;root.right = n3;
        n2.left = n4;n2.right = n5;
        subRoot.left = r2;subRoot.right = r3;

        System.out.println(isSubtree(root, subRoot));
    }

}
